package com.ruoyi.file.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.file.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云文件存储
 * 
 * @author ruoyi
 */
@Primary
@Service
public class AliyunSysFileServiceImpl implements ISysFileService
{
    /**
     * 请求地址
     */
    @Value("${aliyun.url}")
    public String url;

    /**
     * 用户名
     */
    @Value("${aliyun.accessKey}")
    private String accessKey;

    /**
     * 密码
     */
    @Value("${aliyun.secretKey}")
    private String secretKey;

    /**
     * 存储桶名称
     */
    @Value("${aliyun.bucketName}")
    private String bucketName;

    /**
     * 阿里云上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     */
    @Override
    public String uploadFile(MultipartFile file,String folder) throws Exception
    {
        String fileName;
        //判断文件夹是否为空
        if (StringUtils.isNotEmpty(folder)) {
             fileName = folder+"/"+FileUploadUtils.extractFilename(file);
        }else {
            fileName = FileUploadUtils.extractFilename(file);
        }
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(url, accessKey, secretKey);
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            // 上传字符串到OSS。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            if (result!=null){
                return "https://"+bucketName+"."+url+"/"+fileName;
            }
        } catch (OSSException | ClientException e) {
            // 处理异常。
            System.out.println(e.getMessage());
        } finally {
            // 关闭OSSClient。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
